package org.example.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@CrossOrigin(origins = "*")
public class CommonController {

    private static final String UPLOAD_DIR = System.getProperty("user.dir")
            + File.separator + "uploads" + File.separator;

    /**
     * 文件上传
     */
    @PostMapping("/upload")
    public Map<String, Object> upload(@RequestParam("file") MultipartFile file) throws IOException {
        Map<String, Object> result = new HashMap<>();
        if (file == null || file.isEmpty()) {
            result.put("code", 0);
            result.put("msg", "文件为空");
            return result;
        }

        String originalFilename = file.getOriginalFilename();
        String ext = "";
        if (originalFilename != null && StringUtils.hasText(originalFilename) && originalFilename.contains(".")) {
            ext = originalFilename.substring(originalFilename.lastIndexOf('.'));
        }
        String newName = UUID.randomUUID().toString().replace("-", "") + ext;

        File dir = new File(UPLOAD_DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        Path target = Paths.get(UPLOAD_DIR + newName);
        file.transferTo(target.toFile());

        result.put("code", 1);
        result.put("msg", "上传成功");
        result.put("data", newName);
        return result;
    }

    /**
     * 文件下载/预览
     */
    @GetMapping("/download")
    public ResponseEntity<byte[]> download(@RequestParam("name") String name) throws IOException {
        Path path = Paths.get(UPLOAD_DIR + name);
        if (!Files.exists(path)) {
            return ResponseEntity.notFound().build();
        }
        byte[] bytes = Files.readAllBytes(path);
        String contentType = Files.probeContentType(path);
        if (contentType == null) {
            contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        }
        return ResponseEntity.ok()
                .header(HttpHeaders.CACHE_CONTROL, "max-age=2592000")
                .contentType(MediaType.parseMediaType(contentType))
                .body(bytes);
    }
}


